package com.channel.temperature.collect.ui.activity

import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.ToastUtils
import com.hjy.bluetooth.HBluetooth
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener
import com.channel.temperature.collect.app.api.NetUrl
import com.channel.temperature.collect.app.base.BaseActivity
import com.channel.temperature.collect.app.ext.mmkv
import com.channel.temperature.collect.app.util.NetCheckUtils
import com.channel.temperature.collect.app.util.RSAUtils
import com.channel.temperature.collect.app.util.RSAUtils.privateKeyString
import com.channel.temperature.collect.app.util.RSAUtils.publicKeyString
import com.channel.temperature.collect.data.annotation.ValueKey
import com.channel.temperature.collect.data.response.ApiResponseTwo
import com.channel.temperature.collect.data.response.DataBean
import com.channel.temperature.collect.databinding.ActivityHomeBinding
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.hgj.mvvmhelper.base.BaseViewModel
import me.hgj.mvvmhelper.ext.toStartActivity
import rxhttp.toAwait
import rxhttp.wrapper.param.RxHttp
import java.security.KeyFactory
import java.security.PrivateKey
import java.security.PublicKey
import java.security.spec.PKCS8EncodedKeySpec
import java.security.spec.X509EncodedKeySpec
import java.util.Base64
import android.os.Build


class HomeActivity : BaseActivity<BaseViewModel, ActivityHomeBinding>() {
    private lateinit var registerForActivityResult: ActivityResultLauncher<Intent>
    var mHBluetooth: HBluetooth? = null
    lateinit var privateKey: PrivateKey
    lateinit var publicKey: PublicKey
    var phoneSN = ""
    override fun initView(savedInstanceState: Bundle?) {
        try {
            phoneSN = Base64.getEncoder().encodeToString(Build.getSerial().toByteArray())
        } catch (e: SecurityException) {
            phoneSN = ""
        }
        checkPermission()
        checkBlueToothAdapter()
        registerForActivityResult =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                checkBlueToothAdapter()
            }
        //字符串转成密钥对对象
        val keyFactory = KeyFactory.getInstance("RSA")
        //解密的私钥
        privateKey = keyFactory.generatePrivate(
            PKCS8EncodedKeySpec(
                Base64.getDecoder().decode(privateKeyString)
            )
        )
        //加密的公钥
        publicKey = keyFactory.generatePublic(
            X509EncodedKeySpec(
                Base64.getDecoder().decode(publicKeyString)
            )
        )


    }


    private fun checkBlueToothAdapter() {
        var mAdpter: BluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (!mAdpter.isEnabled) {
            MessageDialog.show(
                "提示", "跳转到设置界面打开蓝牙？", "OK", "Cancel"
            ).okButtonClickListener = OnDialogButtonClickListener { dialog, v ->
                ToastUtils.show("点击了ok")
                dialog.dismiss()
                registerForActivityResult.launch(Intent(Settings.ACTION_BLUETOOTH_SETTINGS))
                true
            }
        } else {

        }


    }

    private fun checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            Log.e("高版本", "高版本");
            XXPermissions.with(this) // 申请单个权限
                .permission(Permission.BLUETOOTH_CONNECT).permission(Permission.BLUETOOTH_SCAN)
                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .permission(Permission.READ_PHONE_STATE).permission(Permission.ACCESS_FINE_LOCATION)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: List<String>, all: Boolean) {
                        if (all) {
                            mHBluetooth = HBluetooth.getInstance()
                            mHBluetooth?.let {
                                it.enableBluetooth()
                            }
                            checkAuth()
//                            toHomePage()
//                            ToastUtils.show("同意了全部权限")
                        } else {
//                            ToastUtils.show("未同意全部权限")
                        }
                    }

                    override fun onDenied(permissions: List<String>, never: Boolean) {
                        if (never) {
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(
                                this@HomeActivity, permissions
                            )
                        } else {
                            ToastUtils.show("请通过权限后再操作应用")
                        }
                    }
                })
        } else {
            Log.e("低版本", "低版本");
            XXPermissions.with(this) // 申请单个权限
                .permission(Permission.ACCESS_FINE_LOCATION) // 申请多个权限
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .permission(Permission.READ_EXTERNAL_STORAGE)
                .permission(Permission.WRITE_EXTERNAL_STORAGE)
                .permission(Permission.READ_PHONE_STATE).request(object : OnPermissionCallback {
                    override fun onGranted(permissions: List<String>, all: Boolean) {
                        if (all) {
                            mHBluetooth = HBluetooth.getInstance()
                            mHBluetooth?.let {
                                it.enableBluetooth().bleConfig
                            }
//                            toHomePage()
                            checkAuth()
                        } else {

                        }

                    }

                    override fun onDenied(permissions: List<String>, never: Boolean) {
                        if (never) {
                            ToastUtils.show("android12以下 被永久拒绝授权，请手动授予权限")
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(
                                this@HomeActivity, permissions
                            )
                        } else {
                            ToastUtils.show("请通过权限后再操作应用")
                        }
                    }
                })
        }
    }

    private fun checkAuth() {
        lifecycleScope.launch {
            var cacheAuthValue = mmkv.getString(ValueKey.AUTH_VALUE_KEY, "")
            if (phoneSN.isNullOrEmpty()) {
                var dialog = MessageDialog.show(
                    "提示",
                    "获取授权信息失败，无法激活！",
                    "退出应用",
                )
                dialog.okButtonClickListener = OnDialogButtonClickListener { dialog, v ->
                    dialog.dismiss()
                    this@HomeActivity.finish()
                    true
                }
                dialog.isCancelable = false
            } else {
                if (cacheAuthValue.isNullOrEmpty()) {
                    var dialog = MessageDialog.show(
                        "提示",
                        "未授权，是否授权激活使用APP？\n授权信息：" + phoneSN,
                        "确认",
                        "退出应用"
                    )
                    dialog.okButtonClickListener = OnDialogButtonClickListener { dialog, v ->
                        dialog.dismiss()
                        if (NetCheckUtils.isNetworkAvailable()) {
                            registerDevice()
                        } else {
                            ToastUtils.show("暂无网络")
                        }

                        true
                    }
                    dialog.cancelButtonClickListener = OnDialogButtonClickListener { dialog, v ->
                        dialog.dismiss()
                        this@HomeActivity.finish()
                        true
                    }
                    dialog.isCancelable = false
                } else {
                    if (checkAuthValue()) {
                        toHomePage()
                    } else {
                        var dialog = MessageDialog.show(
                            "提示", "授权校验失败！", "确认", "退出应用"
                        )
                        dialog.okButtonClickListener = OnDialogButtonClickListener { dialog, v ->
                            dialog.dismiss()
                            this@HomeActivity.finish()
                            true
                        }
                        dialog.isCancelable = false
                    }
                }
            }

        }

    }

    private fun registerDevice() {
        WaitDialog.show("激活中...")
        lifecycleScope.launch {

            var encodeString = RSAUtils.encryptByPublicKey(phoneSN, publicKey)
            var dataBean = RxHttp.get(NetUrl.BASE_URL + "/index/appdevices/init_device")
                .add("mData", encodeString).toAwait<ApiResponseTwo<DataBean>>().await()
            if (dataBean.code == 0) {
                mmkv.putString(ValueKey.AUTH_VALUE_KEY, dataBean.data.mData)
                mmkv.putString(ValueKey.AUTH_VALUE_TIME_KEY, dataBean.data.time)
                delay(2000)
                ToastUtils.show("激活成功！")
                WaitDialog.dismiss()
                toHomePage()

            } else {
                WaitDialog.dismiss()
                var dialog = MessageDialog.show(
                    "提示", "激活使用失败，" + dataBean.info, "确认"
                )
                dialog.okButtonClickListener = OnDialogButtonClickListener { dialog, v ->
                    dialog.dismiss()
                    this@HomeActivity.finish()
                    true
                }
                dialog.isCancelable = false
            }

        }
    }

    private fun toHomePage() {
        lifecycleScope.launch {
            delay(1500)
            toStartActivity(CollectHomeActivity::class.java)
            this@HomeActivity.finish()
        }
    }


    private fun checkAuthValue(): Boolean {
        var authKey = mmkv.getString(ValueKey.AUTH_VALUE_KEY, "")
//        var uniqueID = Settings.Secure.getString(
//            appContext.contentResolver, Settings.Secure.ANDROID_ID
//        )
        return authKey?.let { RSAUtils.decrypt(it, privateKeyString) } == phoneSN
    }

    override fun showToolBar() = false
    override fun onDestroy() {
        super.onDestroy()
    }

//    private fun getInfo(paramString: String): String? {
//        val sb = StringBuilder()
//        val telephonyManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
//        if (TelephonyManagerCompat.getPhoneCount(telephonyManager) > 1) {
//            for (slot in 0 until telephonyManager.phoneCount) {
//                sb.append("IMEI " + (slot + 1) + " : ")
//                sb.append(telephonyManager.getDeviceId(slot))
//                sb.append("\n\n")
//            }
//        } else {
//            sb.append("IMEI :" + telephonyManager.deviceId)
//        }
//        return sb.toString()
//    }

}